In [2]:
# Lines in a Python script (*.py file) that begin using the number sign are 
# comments. It is good practice to thoroughly comment your scripts.
# The small initial investment in time to comment your work will save you
# large amounts of time in the long run.
Out[2]:
'\nIt is also possible to add multiline comments using the triple quotes notation.\nTechnically, this is a string and not a comment, but it can effectively be used\nfor long, multiline comments.\n'
In [3]:
#A useful command to run in the IPython console before running a new script
#is '%reset'.  This command will clear all previous variable assignments.
%reset
Once deleted, variables cannot be recovered. Proceed (y/[n])? y
In [5]:
# Addition, subtraction, multiplication, and division
3 + 5
Out[5]:
8
In [6]:
# Alternatively, you can assign the result of the operation to a variable and 
# then print that variable.
x = 3 + 5
print(x)
8
In [8]:
# The synatax for the other common operations are as you'd expect:
y = (3 + 5*2)/4
print(y)
3.25
In [9]:
# You could format your outputs too:
print('y =', y)
y = 3.25
In [10]:
# To do powers, use the ** notation.
print (3**2)

# Note that '^' is not used to evaluate powers in Python.  It is the XOR
# (exclusive OR) logic operator.
9
In [12]:
# Python will accept scientific notation as follows:
hbar = 1.05e-34
kB = 1.38e-23
print('hbar =', hbar, 'Js', '& kB =', kB, 'J/K')
hbar = 1.05e-34 Js & kB = 1.38e-23 J/K
In [13]:
# Some of the other common mathematical functions, like trig functions,
# exponentials, and logs require a module.  For example, cos(1) won't
# work without the math module. I recommend the numPy module. To load the math module, use:
import numpy as np
In [14]:
# We can now evaluate the cosine function using
x = np.cos(1)
print(x)
0.5403023058681398
In [15]:
# Pi and e are also available in the numPy module.
print('pi =', np.pi, '& e =', np.e)
pi = 3.141592653589793 & e = 2.718281828459045
In [17]:
# Here's an inverse trig function
print(np.arctan(9999)/np.pi)
0.4999681658280706
In [18]:
# Here are the exponential and logarithmic functions
print(np.exp(-1))
print(np.log(np.exp(-1))) # natural log, i.e. ln
print(np.log10(10**-2)) # log (base 10)
0.36787944117144233
-1.0
-2.0
In [19]:
# There are two ways to calculate square roots
print(53**0.5)
print(np.sqrt(53))
7.280109889280518
7.280109889280518